package com.lbd99.data.lbd.service;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.lbd99.data.lbd.dao.*;
import com.lbd99.data.lbd.vo.*;
import com.lbd99.data.utils.StrUtil;
import com.lbd99.data.utils.ThreadManager;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lbd99.data.lbd.dao.TUserMapper;
import com.lbd99.data.lbd.dao.TUserOrderRelationMapper;
import com.lbd99.data.lbd.dao.TWalletMapper;

@Service
public class TUserService  {
    @Autowired
    TUserMapper tUserMapper;
    @Autowired
    TWalletMapper tWalletMapper;
    @Autowired
    private TUserOrderRelationMapper tUserOrderRelationMapper;
    @Autowired
    private TIncomeMapper tIncomeMapper;
    @Autowired
    private TTransferLogMapper tTransferLogMapper;
    @Autowired
	SysAccountMapper sysAccountMapper;
    @Autowired
    ProfitService profitService;

   public List<TUser> selectList(Map<String,Object> map){
     return  tUserMapper.selectList(map);
   }


    public  List<Map<String,Object>> selectListMap(Map<String,Object> map){
        return  tUserMapper.selectListMap(map);
    }

    @Transactional
    public  Map<String,Object> updateWallet(final Integer userId,final BigDecimal amount,final String tradePwd,final Integer id){
    	Map<String,Object> map=new HashMap<String,Object>();
    	//判断交易密码是否正确
    	SysAccount sysAccount = sysAccountMapper.selectByPrimaryKey(id);
    	if(!sysAccount.getTradePwd().equals(StrUtil.doEncrypt(tradePwd))){
    		map.put("isSuc",false);
            map.put("msg","交易密码不正确");
            return  map;
    	}
    	TWallet record = tWalletMapper.selectByUserId(userId);
    	//更新账户余额
    	record.setIfip(record.getIfip().add(amount.multiply(new BigDecimal(0.8))));
    	record.setIfiv(record.getIfiv().add(amount.multiply(new BigDecimal(0.2))));
        tWalletMapper.updateByUserId(record);
        //查询用户信息
        TUser user = tUserMapper.selectByPrimaryKey(userId);
        if(user == null){
        	map.put("isSuc",false);
            map.put("msg","用户不存在");
            return  map;
        }
        //===============================================================
//        if(user.getIsUse()==0){
//        	user.setIsUse(1);
//        	tUserMapper.updateByPrimaryKey(user);
//        }
       //===============================================================
        //添加日志记录
        Trecharge trecharge = new Trecharge();
        trecharge.setNum(amount);
        trecharge.setIfip(amount.multiply(new BigDecimal(0.8)));
        trecharge.setIfiv(amount.multiply(new BigDecimal(0.2)));
        trecharge.setUser_id(userId);
        trecharge.setUid(user.getUid());
        tWalletMapper.insertRecharge(trecharge);
        map.put("isSuc",true);
        map.put("msg","操作成功");

        ThreadManager.execute(new Runnable() {
            @Override
            public void run() {
                profitService.transfer(userId,amount.doubleValue());
            }
        });
        return  map;
    }
    
    
    public  List<Map<String,Object>> getParameter(){
        return  tUserMapper.getParameter();
    }
    
    public  Map<String,Object> updateConfig(TConfig tConfig){
        Map<String,Object> map=new HashMap<String,Object>();
        tUserMapper.updateConfig(tConfig);
        map.put("isSuc",true);
        map.put("msg","操作成功");
        return  map;
    }
    
    public  Map<String,Object> insertConfig(TConfig tConfig){
        Map<String,Object> map=new HashMap<String,Object>();
        int mun = tUserMapper.checkConfig(tConfig.getKeys());
        if(mun != 0){
        	map.put("isSuc",false);
            map.put("msg","标识已存在");
            return  map;
        }
        tUserMapper.insertConfig(tConfig);
        map.put("isSuc",true);
        map.put("msg","操作成功");
        return  map;
    }
    
    public List<Map<String,Object>> getExchangeList(Map<String, Object> map){
    	return tUserMapper.getExchangeList(map);
    }

    /**
     * 用户ID，限卖或限转，状态值
     * <p>Title: updateConfinedStatus</p>
     * <p>Description: </p>
     * @param id
     * @param field
     * @param status
     * @return
     */
	public Map<String, Object> updateConfinedStatus(int id, String field, int status) {
		Map<String,Object> resultMap=new HashMap<String,Object>();
		/*if("confined_trade".equals(field) && status==1){//如果是限制买卖，先校验该用户是否有交易进行中的订单
			//0-待收款，1-待付款，2-待确认，3-已取消，4-已成交
			Integer count = tUserOrderRelationMapper.hasTradingOrderByUserId(id);
			if(count>0){
				resultMap.put("isSuc",false);
				resultMap.put("msg","用户交易进行中，稍后再试！");
				return  resultMap;
			}
		}*/
		Map<String,Object> dataMap = new HashMap<String,Object>();
		dataMap.put("id", id);
		dataMap.put("field", field);
		dataMap.put("status", status);
		
		tUserMapper.updateConfinedStatus(dataMap);
		resultMap.put("isSuc",true);
		resultMap.put("msg","操作成功");
        return  resultMap;
	}
	
     //******************************************************************
    //节点范围
    /**
     【小节点】首次享受直接分享人转入矿晶数量的20%，享受第二次以后直接分享人转入矿晶数量的5%进入矿场。
     【中节点】：享受直接分享人首次转入矿晶数量20%的矿场。分享一个享受两层，以此类推，最多享受8层矿晶转入的7%加入到矿场账户。
     【大节点】：享受直接分享人首次转入矿晶数量20%的矿场。分享一个享受两层，以此类推，最 多享受16层矿晶转入的8%加入到矿场账户。
     【超级大节点】享受直接分享人首次转入矿晶数量20%的矿场。享受体系下所有节点转入矿晶的10%加入到矿场账户中。
     推荐奖励：
     小节点	中节点	大节点	超大节点
     矿场数	10万以下	10万-----50万	50万----200万	200万以上
     首次推荐奖励	25%	27%	28%	30%
     后期扩展奖励	5%	5%	2%	1%
     后期扩展奖励层数	4	8	16	32
     注：所有奖励采取烧伤制，比如：8万的小节点推荐20万的中节点，首次推荐奖励为8万÷7X25%=2857,多余的12万不计业绩；
     后期扩展奖励：指的是被推荐人后期接受转账时，给予推荐人的奖励，比如：A推荐了B，B在接受每一笔转账时（80%进入矿晶钱包，20%进入矿场钱包），
     A同时会获得上述表格相应比例的奖励（根据转入的总金额---80%矿晶+20%的矿场计算比例），多出部分不计业绩。
     */
    public void nodeRange( int otherUserId, double ifipNum){
        //被转矿晶的用户对象
        TUser otherUser=tUserMapper.selectByPrimaryKey(otherUserId);
        if (otherUser.getpId()==-1){ //说明被转矿晶已经是顶级用户
            return;
        }
        TWallet wallet=tWalletMapper.selectByUserId(otherUserId);
        if(wallet.getIfiv().doubleValue()<10*10000){ //10万以下,最多4层
            //如果首次转账，则上级奖励25%，后期奖励5%，最多4层
            parentIncome(otherUserId,ifipNum,0.25,0.05,4);
        }else if(wallet.getIfiv().doubleValue()>=10*10000 && wallet.getIfiv().doubleValue()<50*10000){//10万-----50万，最多8层
            parentIncome(otherUserId,ifipNum,0.27,0.05,8);
        }else if(wallet.getIfiv().doubleValue()>=50*10000 && wallet.getIfiv().doubleValue()<200*10000){//50万----200万，最多16层
            parentIncome(otherUserId,ifipNum,0.28,0.02,16);
        }else if(wallet.getIfiv().doubleValue()>=200*10000){//200万以上，最多32层
            parentIncome(otherUserId,ifipNum,0.3,0.01,32);
        }
    }
    private  void parentIncome(int otherUserId, double ifipNum,double  rateBig,double rateSmall,int resultNumLevel){
        Map  map2=new HashMap<>();
        //0-转入，1-转出
        map2.put("type",0);
        map2.put("userId",otherUserId);
        int count=tTransferLogMapper.selectTransferCount(map2);
        double rate=0.00;
        if (count==0){ //说明是第一次转账
            rate=rateBig;
        }else{  //说明不是第一次转账
            rate=rateSmall;
        }
        int sonNum=tUserMapper.selectCountByPid(otherUserId);
        int resultNum=0;
        if (sonNum>resultNumLevel/2){  //后期扩展奖励层数4层,只限定4层
            resultNum=resultNumLevel;
        }else{
            resultNum=sonNum*2;
        }
        if (resultNum==0){
            resultNum=1;
        }
        String parentIds=	getParentIds(otherUserId,"",resultNum);
        String[]  parentId=  parentIds.split(",");
        int autoCount=1;
        if (parentId!=null && parentId.length>0) {
            for (int i=0;i<parentId.length;i++) {
                if (i==0){  //直接推荐人
                    String parentIdStr= parentId[i];
                    TWallet wallet2=tWalletMapper.selectByUserId(Integer.parseInt(parentIdStr));
                    TWallet wallet3=new TWallet();
                    wallet3.setUserId(Integer.parseInt(parentIdStr));
                    wallet3.setIfiv(new BigDecimal(wallet2.getIfiv().doubleValue()+StrUtil.keep4decimal(ifipNum*0.2)));  //20%矿场
                    wallet3.setIfip(new BigDecimal(wallet2.getIfip().doubleValue()+StrUtil.keep4decimal(ifipNum*0.05)) ); //5%矿晶
                    tWalletMapper.updateByUserId(wallet3);

                    TIncome record=new TIncome();
                    record.setUserId(-1);
                    record.setCreateBy("后台充值");
                    record.setpId(Integer.parseInt(parentIdStr));
                    record.setUpdateTime(new Date());
                    record.setCreateTime(new Date());
                    record.setIfipNum(ifipNum);
                    record.setOtherUserId(otherUserId);
                    record.setParentIncomeIfiv(StrUtil.keep4decimal(ifipNum*0.2));
                    record.setParentIncomeIfip(StrUtil.keep4decimal(ifipNum*0.05));
                    record.setUpdateBy("后台充值");
                    tIncomeMapper.insertSelective(record);
                }else{  //不是直接推荐人
                    String parentIdStr= parentId[i];
                    TWallet wallet2=tWalletMapper.selectByUserId(Integer.parseInt(parentIdStr));
                    TWallet wallet3=new TWallet();
                    wallet3.setUserId(Integer.parseInt(parentIdStr));
                    double incomeJS=ifipNum*0.2*(Math.pow(rate,autoCount));
                    wallet3.setIfiv(new BigDecimal(wallet2.getIfiv().doubleValue()+ StrUtil.keep4decimal(incomeJS)));
                    tWalletMapper.updateByUserId(wallet3);
                    TIncome record=new TIncome();
                    record.setUserId(-1);
                    record.setCreateBy("后台充值");
                    record.setpId(Integer.parseInt(parentIdStr));
                    record.setUpdateTime(new Date());
                    record.setCreateTime(new Date());
                    record.setIfipNum(ifipNum);
                    record.setOtherUserId(otherUserId);
                    record.setParentIncomeIfiv(StrUtil.keep4decimal(incomeJS));
                    record.setUpdateBy("后台充值");
                    tIncomeMapper.insertSelective(record);
                    autoCount++;
                }
            }
        }
    }
    /**
     *  获得上级所有的节点
     * @param id
     * @param sumResult
     * @param level
     * @return
     */
    private  String getParentIds(int id,String sumResult,int level){
        Integer pid= tUserMapper.selectByPrimaryKey(id).getpId();
        if (pid.intValue()==-1 || level==0 ){
            return  sumResult;
        }else{
            String[] sumResultArr=sumResult.split(",");
            if ((sumResultArr.length >=level) && (!"".equals(sumResult))){
                return  sumResult;
            }
            sumResult=sumResult+pid+",";
            return getParentIds(pid,sumResult,level);
        }
    }
    
    public List<Map<String, Object>> getExchangeListWeek(Map<String, Object> map) {
		return tUserMapper.getExchangeListWeek(map);
	}



    //*******************************更新算法2******************************************************************************

    public void nodeRange2(int otherUserId, double ifipNum) {
        //被转矿晶的用户对象
        TUser otherUser=tUserMapper.selectByPrimaryKey(otherUserId);
        if (otherUser.getpId()==-1){ //说明被转矿晶已经是顶级用户
            return;
        }
        TWallet wallet2=tWalletMapper.selectByUserId(otherUserId);
        double p=wallet2.getIfiv().doubleValue();
        int level=4;
//        if(p<10*10000){
//            level=4;
//        }else if(p>=10*10000 && p<50*10000){
//            level=8;
//        }else if(p>=50*10000 && p<200*10000){
//            level=16;
//        }else if(p>=200*10000){
//            level=32;
//        }
//        parentIncome2(otherUserId,ifipNum,level);

        int sonNum=tUserMapper.selectCountByPid(otherUserId);
        if(p<10*10000){
            if (sonNum*2>4){
                level=4;
            }else{
                level=sonNum*2;
            }
            if (level==0){
                level=1;
            }
            parentIncome2(otherUserId,ifipNum,level);
        }else if(p>=10*10000 && p<50*10000){
            if (sonNum*2>8){
                level=8;
            }else{
                level=sonNum*2;
            }
            if (level==0){
                level=1;
            }
            parentIncome2(otherUserId,ifipNum,level);
        }else if(p>=50*10000 && p<200*10000){
            if (sonNum*2>16){
                level=16;
            }else{
                level=sonNum*2;
            }
            if (level==0){
                level=1;
            }
            parentIncome2(otherUserId,ifipNum,level);
        }else if(p>=200*10000){
            if (sonNum*2>32){
                level=32;
            }else{
                level=sonNum*2;
            }
            if (level==0){
                level=1;
            }
            parentIncome2(otherUserId,ifipNum,level);
        }
    }
    private  void parentIncome2( int otherUserId, double ifipNum,int resultNumLevel){
     //   TUser otherUser=tUserMapper.selectByPrimaryKey(otherUserId);
        String parentIds=	getParentIds(otherUserId,"",resultNumLevel);
        if (parentIds==null || "".equals(parentIds)){
            return;
        }
        String[]  parentId=  parentIds.split(",");
        double resultIFIV=0.0;
        if (parentId!=null && parentId.length>0) {
            for (int i=0;i<parentId.length;i++) {
                if (i==0){  //直接推荐人(上一级)
                    String parentIdStr= parentId[i];
                    TWallet wallet2=tWalletMapper.selectByUserId(Integer.parseInt(parentIdStr));
                    TUser parentUser=tUserMapper.selectByPrimaryKey(Integer.parseInt(parentIdStr));
                    Map  map2=formatIFIVGetMap(wallet2.getIfiv().doubleValue());
                    Double ifip1= (Double) map2.get("ifip");
                    Double ifiv1= (Double) map2.get("ifiv");

                    double ifipNum2=ifipNum;
                    double ifiv7=StrUtil.keep4decimal(wallet2.getIfiv().doubleValue()/7);
                    if (ifipNum>ifiv7){
                        ifipNum2=ifiv7;
                    }
                    //直接上级要有收益
                    if (ifipNum2==0){
                        ifipNum2=ifipNum;
                    }
                    TWallet wallet3=new TWallet();
                    wallet3.setUserId(Integer.parseInt(parentIdStr));
                    if (parentUser.getIsUse()==0){
                        wallet3.setIfiv(new BigDecimal( wallet2.getIfiv().doubleValue()+ StrUtil.keep4decimal(ifipNum2*ifiv1)));  //20%矿场
                    }
                    wallet3.setIfip(new BigDecimal(wallet2.getIfip().doubleValue()+StrUtil.keep4decimal(ifipNum2*ifip1)) ); //5%矿晶
                    tWalletMapper.updateByUserId(wallet3);

                    //#######添加到收益表#########【start】#####################################################
                    TIncome record=new TIncome();
                    record.setUserId(-1);
                    record.setCreateBy("后台充值");
                    record.setpId(Integer.parseInt(parentIdStr));
                    record.setUpdateTime(new Date());
                    record.setCreateTime(new Date());
                    record.setIfipNum(ifipNum);
                    record.setOtherUserId(otherUserId);
                    record.setParentIncomeIfip(StrUtil.keep4decimal(ifipNum2*ifip1));
                    Map map=new HashMap<>();
                    map.put("ifipNum2",ifipNum2);
                    if (parentUser.getIsUse()==0){
                        map.put("ifivRate",ifiv1);
                        record.setParentIncomeIfiv(StrUtil.keep4decimal(ifipNum2*ifiv1));
                    }
                    map.put("ifipRate",ifip1);
                    record.setUpdateBy(JSON.toJSONString(map));
                    tIncomeMapper.insertSelective(record);
                    //#######添加到收益表#########【end】#####################################################

                    //---------------添加到转账记录表中【转入】------------------start-----------------------------
                    TTransferLog tTransferLog2 = new TTransferLog();
                    tTransferLog2.setCreateTime(new Date());
                    tTransferLog2.setUpdateBy("【后台充值收益】被充值用户otherUserId:"+otherUserId+",兑换矿晶为:"+ifipNum);
                    tTransferLog2.setUpdateTime(new Date());
                    tTransferLog2.setIfip(StrUtil.keep4decimal(ifipNum2*ifiv1));
                    tTransferLog2.setIfiv(0.0);
                    if (parentUser.getIsUse()==0){
                        tTransferLog2.setIfiv(StrUtil.keep4decimal(ifipNum2*ifiv1));
                        tTransferLog2.setCreateBy("0");
                    }else{
                        tTransferLog2.setCreateBy("1");
                    }

                    //0-转入，1-转出
                    tTransferLog2.setType(0);//转入
                    tTransferLog2.setUserId(Integer.parseInt(parentIdStr));
                    tTransferLog2.setUid(wallet2.getUid());
                    tTransferLogMapper.insert(tTransferLog2);
                    //---------------添加到转账记录表中【转入】------------------end-----------------------------

                }

//                else if(i==1){ //第二级也会有收益(上二级)
//                    String parentIdStr= parentId[i];
//                    TWallet wallet2=tWalletMapper.selectByUserId(Integer.parseInt(parentIdStr));
//                    double ifipNum2=ifipNum;
//                    double ifiv7=StrUtil.keep4decimal(wallet2.getIfiv().doubleValue()/7);
//                    if (ifipNum>ifiv7){
//                        ifipNum2=ifiv7;
//                    }
//                    double rate=formatIFIV(wallet2.getIfiv().doubleValue());
//
//                    resultIFIV=wallet2.getIfiv().doubleValue();
//                    TWallet wallet3=new TWallet();
//                    wallet3.setUserId(Integer.parseInt(parentIdStr));
//                   // wallet3.setIfiv(new BigDecimal(wallet2.getIfiv().doubleValue()+ StrUtil.keep4decimal(ifipNum2*rate)));
//                    wallet3.setIfip(new BigDecimal(wallet2.getIfip().doubleValue()+ StrUtil.keep4decimal(ifipNum2*rate)));
//                    tWalletMapper.updateByUserId(wallet3);
//                    //#######添加到收益表#########【start】#####################################################
//                    TIncome record=new TIncome();
//                    record.setUserId(-1);
//                    record.setCreateBy("后台充值");
//                    record.setpId(Integer.parseInt(parentIdStr));
//                    record.setUpdateTime(new Date());
//                    record.setCreateTime(new Date());
//                    record.setIfipNum(ifipNum);
//                    record.setOtherUserId(otherUserId);
//                    record.setParentIncomeIfiv(StrUtil.keep4decimal(ifipNum2*rate));
//                    Map map=new HashMap<>();
//                    map.put("ifipNum2",ifipNum2);
//                    map.put("ifipRate",rate);
//                    record.setUpdateBy(JSON.toJSONString(map));
//                    tIncomeMapper.insertSelective(record);
//                    //#######添加到收益表#########【end】#####################################################
//
//                    //---------------添加到转账记录表中【转入】------------------start-----------------------------
//                    TTransferLog tTransferLog2 = new TTransferLog();
//                    tTransferLog2.setCreateTime(new Date());
//                    tTransferLog2.setCreateBy("1");
//                    tTransferLog2.setUpdateBy("【后台充值收益】被充值用户otherUserId:"+otherUserId+",兑换矿晶为:"+ifipNum);
//                    tTransferLog2.setUpdateTime(new Date());
//                    tTransferLog2.setIfip(StrUtil.keep4decimal(ifipNum2*rate));
//                    tTransferLog2.setIfiv(0.0);
//                    //0-转入，1-转出
//                    tTransferLog2.setType(0);//转入
//                    tTransferLog2.setUserId(Integer.parseInt(parentIdStr));
//                    tTransferLog2.setUid(wallet2.getUid());
//                    tTransferLogMapper.insert(tTransferLog2);
//                    //---------------添加到转账记录表中【转入】------------------end-----------------------------
//
//                }

                else{  //不是直接推荐人(上一级 以上)
                    String parentIdStr=parentId[i];
                    TWallet wallet2=tWalletMapper.selectByUserId(Integer.parseInt(parentIdStr));
                    if (resultIFIV>wallet2.getIfiv().doubleValue()){
                        continue;
                    }
                    resultIFIV=wallet2.getIfiv().doubleValue();
//                    int sonNum=tUserMapper.selectCountByPid(Integer.parseInt(parentIdStr));
//                    TUser parentUser=tUserMapper.selectByPrimaryKey(Integer.parseInt(parentIdStr));
//                    int level=otherUser.getLevel()-parentUser.getLevel();
//                    if (level>sonNum*2){
//                        continue;
//                    }
                    boolean bool= isIntercept(Integer.parseInt(parentIdStr));
                    if (bool==false){
                        continue;
                    }
                    TWallet wallet3=new TWallet();
                    wallet3.setUserId(Integer.parseInt(parentIdStr));
                    double ifipNum2=ifipNum;
                    double ifiv7=StrUtil.keep4decimal(wallet2.getIfiv().doubleValue()/7);
                    if (ifipNum>ifiv7){
                        ifipNum2=ifiv7;
                    }
                    double rate=getIFIP(i+1);   //formatIFIV(wallet2.getIfiv().doubleValue());
                    //wallet3.setIfiv(new BigDecimal(wallet2.getIfiv().doubleValue()+ StrUtil.keep4decimal(ifipNum2*rate)));
                    wallet3.setIfip(new BigDecimal(wallet2.getIfip().doubleValue()+ StrUtil.keep4decimal(ifipNum2*rate)));
                    tWalletMapper.updateByUserId(wallet3);
                    //#######添加到收益表#########【start】#####################################################
                    TIncome record=new TIncome();
                    record.setUserId(-1);
                    record.setCreateBy("后台充值");
                    record.setpId(Integer.parseInt(parentIdStr));
                    record.setUpdateTime(new Date());
                    record.setCreateTime(new Date());
                    record.setIfipNum(ifipNum);
                    record.setOtherUserId(otherUserId);
                   // record.setParentIncomeIfiv(StrUtil.keep4decimal(ifipNum2*rate));
                    record.setParentIncomeIfip(StrUtil.keep4decimal(ifipNum2*rate));
                    Map map=new HashMap<>();
                    map.put("ifipNum2",ifipNum2);
                    map.put("ifipRate",rate);
                    record.setUpdateBy(JSON.toJSONString(map));
                    tIncomeMapper.insertSelective(record);
                    //#######添加到收益表#########【end】#####################################################

                    //---------------添加到转账记录表中【转入】------------------start-----------------------------
                    TTransferLog tTransferLog2 = new TTransferLog();
                    tTransferLog2.setCreateTime(new Date());
                    tTransferLog2.setCreateBy("1");
                    tTransferLog2.setUpdateBy("【后台充值收益】被充值用户otherUserId:"+otherUserId+",兑换矿晶为:"+ifipNum);
                    tTransferLog2.setUpdateTime(new Date());
                    tTransferLog2.setIfip(StrUtil.keep4decimal(ifipNum2*rate));
                    tTransferLog2.setIfiv(0.0);
                    //0-转入，1-转出
                    tTransferLog2.setType(0);//转入
                    tTransferLog2.setUserId(Integer.parseInt(parentIdStr));
                    tTransferLog2.setUid(wallet2.getUid());
                    tTransferLogMapper.insert(tTransferLog2);
                    //---------------添加到转账记录表中【转入】------------------end-----------------------------
                }
            }
        }
    }


    
	public Map<String, Object> getRechargeRecord(int page,int rows,String phone,String nickName,String rootUserId){
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("phone", phone);
		map.put("nickName", nickName);
		map.put("rootUserId", rootUserId);
    	PageHelper.startPage(page, rows);
    	List<Map<String,Object>> list = tUserMapper.getRechargeRecord(map);
    	PageInfo<Map<String,Object>> pages = new PageInfo<Map<String,Object>>(list); 
    	result.put("total", pages.getTotal());
		result.put("rows", pages.getList());
		return result;
	}
	
	public TUser selectByPhone(String tel) {
		return tUserMapper.selectByPhone(tel);
	}

	//根据用户id查出该用户伞下的ID集合(包含自身)
	public List<Integer> selectTreeIds(Integer id) {
		return tUserMapper.selectTreeIds(id);
	}


    /**
     *
     *
     * 				小节点			中节点			大节点		超大节点
     矿场数			10万以下	10万-----50万	50万----200万	200万以上
     *首次推荐奖励	 25%			27%				28%				30%
     * @param p  矿场
     * @return
     */
    private  Map formatIFIVGetMap(double p){
        Map map=new HashMap<>();
        if(p<10*10000){
            map.put("ifip",0.05);
            map.put("ifiv",0.2);
        }else if(p>=10*10000 && p<50*10000){
            map.put("ifip",0.07);
            map.put("ifiv",0.2);
        }else if(p>=50*10000 && p<200*10000){
            map.put("ifip",0.08);
            map.put("ifiv",0.2);
        }else if(p>=200*10000){
            map.put("ifip",0.1);
            map.put("ifiv",0.2);
        }
        return  map;
    }



    private  boolean  isIntercept(Integer parentId){
        boolean result=false;
        TWallet wallet2=tWalletMapper.selectByUserId(parentId);
        int sonNum=tUserMapper.selectCountByPid(parentId);
        double p=wallet2.getIfiv().doubleValue();
        if(p<10*10000){  //小节点
            if (sonNum>=4){  //大于等于4个才满足收益
                result=true;
            }
        }else if(p>=10*10000 && p<50*10000){ //中节点
            if (sonNum>=6){ //大于等于6个才满足收益
                result=true;
            }
        }else if(p>=50*10000 && p<200*10000){  //大节点
            if (sonNum>=8){ //大于等于8个才满足收益
                result=true;
            }
        }else if(p>=200*10000){   //超大节点
            if (sonNum>=10){  //大于等于10个才满足收益
                result=true;
            }
        }
        return  result;
    }
    
    
    public Map<String, Object> updateUserPhone(String phone,int id){
    	Map<String,Object> map = new HashMap<String,Object>();
    	//判断手机号码是否已经注册
    	int flag = tUserMapper.checkUserPhone(phone);
    	if(flag > 0){
    		map.put("isSuc",false);
    		map.put("msg","该手机号码已注册");
    		return map;
    	}
    	int num = tUserMapper.updateUserPhone(phone,id);
    	if(num != 1){
    		map.put("isSuc",false);
    		map.put("msg","操作失败");
    		return map;
    	}
    	map.put("isSuc",true);
		map.put("msg","操作成功");
		return map;
    }
    
    //充值矿晶矿场 
    public Map<String, Object> rechargeUserIfipb(BigDecimal ifiv,BigDecimal ifip,int id){
    	TUser tuser = tUserMapper.selectByPrimaryKey(id);//查询出用户
    	Map<String, Object> map = new HashMap<String,Object>();
    	Map<String, Object> result = new HashMap<String,Object>();
    	map.put("ifiv", ifiv);
    	map.put("ifip", ifip);
    	map.put("id", id);
    	int num = tWalletMapper.rechargeUserIfipb(map);
    	//需要产生充值记录
    	Trecharge trecharge = new Trecharge();
    	trecharge.setUser_id(id);
    	trecharge.setUid(tuser.getUid());
    	trecharge.setNum(new BigDecimal(0));
    	trecharge.setIfip(ifip);
    	trecharge.setIfiv(ifiv);
    	trecharge.setCreate_time(new Date());
    	tUserMapper.insertRechargeLog(trecharge);
    	
    	if(num != 1){
    		result.put("isSuc",false);
    		result.put("msg","操作失败");
    		return result;
    	}
    	result.put("isSuc",true);
    	result.put("msg","操作成功");
		return result;
    }


    /**
     0-4层       5%
     5-8层       5%
     9-16层      2%
     17-32层     1%
     */

    public  double  getIFIP(int level){
        double result=0.0;
        if (level>=0 && level<=4){
            result=0.05;
        }else if(level>=5 && level<=8){
            result=0.05;
        }else if(level>=9 && level<=16){
            result=0.02;
        }else if(level>=17 && level<=32){
            result=0.01;
        }
        return  result;
    }


	public Map<String, Object> confineTradeCountSave(Integer id, Integer count_trade) {
		Map<String, Object> result = new HashMap<String,Object>();
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("id", id);
		map.put("count_trade", count_trade);
		try {
			tUserMapper.confineTradeCountSave(map);
			result.put("isSuc",true);
	    	result.put("msg","操作成功");
		} catch (Exception e) {
			result.put("isSuc",false);
	    	result.put("msg","操作失败");
		}
		return result;
	}

    public Map<String, Object> updatePwd(Integer id,String pwd,String trade_pwd) {
        Map<String, Object> result = new HashMap<String,Object>();
        try {
            TUser record=new TUser();
            record.setId(id);
            if(StringUtils.isNotBlank(pwd)){
            	record.setLoginPwd(StrUtil.doEncrypt(pwd));
            }
            if(StringUtils.isNotBlank(trade_pwd)){
            	record.setTradePwd(StrUtil.doEncrypt(trade_pwd));
            }
            tUserMapper.updateByPrimaryKeySelective(record);
            result.put("isSuc",true);
            result.put("msg","操作成功");
        } catch (Exception e) {
            result.put("isSuc",false);
            result.put("msg","操作失败");
        }
        return result;
    }


	public List<Map<String, Object>> getChildUserByParentId(Map<String, Object> datamap) {
		return tUserMapper.getChildUserByParentId(datamap);
	}


    /**
     *   根据矿场计算节点对应的 奖励
     * @param p  矿场
     * @return
     */
//    private  double formatIFIV(double p){
//        double d=0.0;
//        if(p<10*10000){
//            d=0.05;
//        }else if(p>=10*10000 && p<50*10000){
//            d=0.05;
//        }else if(p>=50*10000 && p<200*10000){
//            d=0.02;
//        }else if(p>=200*10000){
//            d=0.01;
//        }
//        return  d;
//    }

}
